<?php
/**
 * 产品价格分析
 *
 * PHP Version 5
 *
 * @package    Ecga
 * @subpackage Models
 * @author     Farmer.Li <lixu_01@126.com>
 * @copyright  2010 Xingchangxinda Inc.
 * @version    SVN:$Id$
 */
namespace Project\Apps\Ecga\Models\Table;

use Project\Apps\Ecga\Library\Visitor;


/**
 * 类别销售统计表
 *
 * @package   Ecga
 * @author    Farmer.Li <lixu_01@126.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: v0.1
 */
class ProductAnalyse extends EcgaTable
{
    /**
     * 表名称
     */
    public $name = '产品价格分析';
    
    public $desc = '按SKU和站点分析产品价格走向。';
    
    public $defaultSort = '';
    
    /**
     * 所有项目
     */
    protected $projects = array();
    /**
     * 当前查看的项目
     */
    protected $project = array();
    /**
     * 站点列表
     */
    protected $sites = array();
    /**
     * 构造
     *
     * @return void
     */
    public function __construct()
    {
        $this->projects = $this->getProjects();
        //$this->sites = $this->getSites();
        parent::__construct();
    }
    
    /**
     * 设置数据表头
     *
     * @return void
     */
    protected function setHeaderGroups()
    {
        $this->headerGroups = array(
            'SKU信息' => array(
                'models' => array(
                    'name' => 'Model',
                    'lock' => 'true'
                ),
                'level' => array(
                    'name' => '星级',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'sku' => array(
                    'name' => 'SKU',
                    'lock' => 'true'
                ),
                'pn' => array(
                    'name' => 'P/N',
                    'lock' => 'true'
                ),
                'dsp' => array(
                    'name' => '总代出货价',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'srp' => array(
                    'name' => '厂商指导价',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'mop' => array(
                    'name' => '协定价',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'afp' => array(
                    'name' => '全网最低价',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'gap' => array(
                    'name' => '差价',
                    'class' => 'floatRight',
                    'lock' => 'true'
                ),
                'tbfp' => array(
                    'name' => '淘宝最低价',
                    'class' => 'floatRight'
                ),
            )
        );
        $date = $this->filters['date']->value;
        $batch = $this->filters['batch']->value;
        $tag = $this->filters['tag']->value;
        $sites = $this->getSites($this->filters['projectId']->value);
        if (is_array($sites)) {
            foreach ($sites as $value) {
                $data = array(
                    'name' => $value['cname'],
                    'class' => 'floatRight',
                    'link' => 'siteanalyse.php?siteId=' . $value['id'] .
                        '&projectId=' . $this->project['id'] . '&batch=' . $batch .
                        '&date=' . $date
                );
                if ($value['region'] != 0 ) {
                    $data['name'] = $value['cname'].self::checkRegion($value['region']);
                }
                $this->headerGroups['各渠道价格'][$value['id']] = $data;
                if ($value['tag'] != $tag && '0' != $tag) {
                    unset($this->headerGroups['各渠道价格'][$value['id']]);
                }
            }
        }
    }
    
    /**
     * 初始化筛选器
     *
     * @return void
     */
    protected function initFilters()
    {
        $filters = array(
                'projectId' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => 0,
                    'bind' => $this->arrayToOptions($this->projects, 'id', 'projectName'),
                    'caption' => '项目',
                    'name' => 'projectId'
                ),
                'date' => array(
                    'type' => Filter::FILTER_TYPE_DATE,
                    'default' => date('Y-m-d'),
                    'caption' => '日期',
                    'validator' => new DateTimeValidator
                ),
                'batch' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => '',
                    'caption' => '批次',
                    'name' => 'batch'
                ),
                'models' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => '0',
                    'bind' => $this->arrayToOptions($this->getModels(), 'modelId', 'modelName'),
                    'caption' => 'Model',
                    'name' => 'models'
                ),
                'skus' => array(
                    'name' => 'model',
                    'type' => Filter::FILTER_TYPE_TEXT,
                    'caption' => '查看指定P/N,多个P/N使用" "(空格)分隔',
                    'size' => 60,
                    'readOnly' => false
                ),
                'level' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => '0',
                    'bind' => $this->arrayToOptions(self::levelArray(), 'id', 'levelName'),
                    'caption' => '星级',
                    'name' => 'level'
                ),
                'tag' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => '0',
                    'bind' => $this->arrayToOptions(self::tagArray(), 'id', 'tagName'),
                    'caption' => '组群',
                    'name' => 'tag'
                ),
            );

        if ( 1 == count($this->projects)) {
            foreach ($this->projects as $value) {
                $batch = $value['id'];
            }
            $filters['batch']['bind'] = $this->arrayToOptions(self::getBatch($batch), 'id', 'name');
        }
        if (1 == count($this->projects) && $this->projects[1]['id'] != 1) {
            unset($filters['models']);
            unset($filters['level']);
            unset($filters['tag']);
        }
        $this->filters = Filter::createFromMultiArray($filters);
    }
    
    /**
     * 填充数据
     *
     * @return void
     */
    protected function fillData()
    {
        $date = $this->filters['date']->value;
        $batch = $this->filters['batch']->value;
        $models = $this->filters['models']->value;
        $level = $this->filters['level']->value;
        //将全角空格替换为半角空格
        $this->filters['skus']->value = str_replace('　', ' ', $this->filters['skus']->value);
        $this->filters['skus']->value = trim($this->filters['skus']->value);
        if (!$this->filters['skus']->value && !$this->project) {
            return;
        }
        $skus = explode(' ', $this->filters['skus']->value);
        if ($level != 0) {
            $skusByLevel = model('skus')->getSkuByLevel($level);
            $skus = array_merge($skus, $skusByLevel);
        }
        if (!empty($models)) {
            $skusByModel = model('skus')->getSkuByModel($models);
            $skus = array_merge($skus, $skusByModel);
        }

        $skus = array_filter($skus);
        $data = model('SkuPriceLogs')->getByProjectId($this->project['id'], $date, $batch);
        if ($data) {
            foreach ($data as $value) {
                if ($skus != array() && !in_array($value->sku, $skus)) {
                    continue;
                }
                if (!isset($this->rows[$value->sku])) {
                    $this->rows[$value->sku] = $this->createDataRow();
                }
                $this->rows[$value->sku]['sku'] = $value->skuInfo->title; // sku 指向title  罗技

                $this->rows[$value->sku]['projectId'] = $this->project['id'];
                $this->rows[$value->sku]['batch'] = $batch;
                $this->rows[$value->sku]['date'] = $date;
                $mop = !empty($value->skuInfo->mop) ? $value->skuInfo->mop : $value->skuInfo->srp * parent::SRP_MOP;
                //$this->rows[$value->sku]['title'] = $value->skuInfo->title;      //title 一列没用了   罗技
                $this->rows[$value->sku]['srp'] = $value->skuInfo->srp;
                $this->rows[$value->sku]['mop'] = $mop;
                $this->rows[$value->sku][$value->siteId] = $value['price'];
                $this->rows[$value->sku]['title_' . $value->siteId] = $value['title'];
                $this->rows[$value->sku]['url_' . $value->siteId] = $value['skuUrl'];
                
                $this->rows[$value->sku]['models'] = $value->skuInfo->model;
                $this->rows[$value->sku]['pn'] = $value->skuInfo->sku;   //pn  指向的是sku  罗技
                $this->rows[$value->sku]['level'] = $value->skuInfo->level.'星';
                $this->rows[$value->sku]['dsp'] = $value->skuInfo->dsp;
                
                $tempGap = $value['price'];
                if (!isset($this->rows[$value->sku]['afp'])) {
                    $this->rows[$value->sku]['afp'] = $tempGap;
                }
                if ($tempGap < $this->rows[$value->sku]['afp']) {
                    $this->rows[$value->sku]['afp'] = $tempGap;
                }
                $this->rows[$value->sku]['gap'] = abs($mop - $this->rows[$value->sku]['afp']);
                
                if (self::checkSkuUrl($value['skuUrl'])) {
                    $tempTbfp = $value['price'];
                    if (!isset($this->rows[$value->sku]['tbfp'])) {
                        $this->rows[$value->sku]['tbfp'] = $tempTbfp;
                    }
                    if ($tempTbfp < $this->rows[$value->sku]['tbfp']) {
                        $this->rows[$value->sku]['tbfp'] = $tempTbfp;
                    }
                }
            }
        }
    }
    /**
     * 生成图表可用数据
     *
     * @return void
     */
    protected function createChartData()
    {
        
    }
    
    /**
     * 生成数据表
     * 
     * @return void
     */
    public function generate()
    {
        if (!$this->filters['projectId']->value) {
            return;
        }
        $this->project = $this->projects[$this->filters['projectId']->value];
        if ($this->project) {
            $this->filters['batch']->bind = $this->project['batchConfig'];
            if ('' === $this->filters['batch']->value) {
                $this->filters['batch']->value = current($this->project['batchConfig']);
            }
        }
        parent::generate();
    }
    
    /**
     * 验证渠道是否是淘宝
     *
     * @param string $skuUrl 渠道链接
     * 
     * @return bool
     */
    public static function checkSkuUrl($skuUrl) 
    {
        $return = false;
        if (!empty($skuUrl)) {
            if (stripos($skuUrl, 'tmall.com') > -1 || stripos($skuUrl, 'taobao.com') > -1) {
                $return = true;
            }
        }
        return $return;
    }
    
    /**
     * 验证渠道东西南北区
     *
     * @param int $region 地域
     * 
     * @return string
     */
    public static function checkRegion($region)
    {
        $return = '';
        switch ($region) {
        case 1:
            $return = '(东)';
            break;
        case 2:
            $return = '(西)';
            break;
        case 3:
            $return = '(南)';
            break;
        case 4:
            $return = '(北)';
            break;
        }
        return $return;
    }
    /**
     * 获取项目采集批次信息
     * 
     * @param int $projectId 项目Id
     * 
     * @return void
     */
    public static function getBatch($projectId )
    {
    
        $project = model('Projects')->get($projectId);

        if (!$project) {
            return ;
        }

        $batch = explode(',', $project->batchConfig);
        foreach ($batch as $value) {
            $batchs[] = array(
                'id' => $value,
                'name' => $value
            ); 
        }
        return $batchs;
    }
    /**
     * 产品星级
     *
     * @return array
     */
    public static function levelArray()
    {
        $return = array(
            '1' => '一星',
            '2' => '二星',
            '3' => '三星'
        );
        foreach ($return as $key => $value) {
            $levelArray[] = array(
                'id' => $key,
                'levelName' => $value
            ); 
        }
        return $levelArray;
    }
    /**
     * 渠道分组
     *
     * @return array
     */
    public static function tagArray()
    {
        $return = model('sites')->getTag();
        foreach ($return as $key => $value) {
            $tagArray[] = array(
                'id' => $value[0],
                'tagName' => $value['tag']
            ); 
        }
        return $tagArray;
    }
}